package com.ganzi.ganziserver.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ganzi.ganziserver.core.Role;
import com.ganzi.ganziserver.core.User;
import com.ganzi.ganziserver.service.RoleService;
import com.ganzi.ganziserver.service.SendService;
import com.ganzi.ganziserver.service.UserService;
import com.ganzi.ganziserver.shiro.filter.KickoutSessionControlFilter;
import com.ganzi.ganziserver.shiro.redis.OtherCache.UserCache;
import com.ganzi.ganziserver.utils.OtherException;
import com.ganzi.ganziserver.utils.ReturnMap;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.apache.shiro.codec.Base64;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.session.mgt.DefaultSessionKey;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;


/**
 * 用户操作controller
 * */
@RestController
@RequestMapping("/user")
public class LoginController {
    private static Logger logger = LoggerFactory.getLogger(LoginController.class);
    @Autowired
    UserService userService;
    @Autowired
    RoleService roleService;
    @Autowired
    UserCache cache;
    @Autowired
    SendService sendService;


    /**
     * 准备登录
     * */
    @RequestMapping(value ="/readylogin",method = {RequestMethod.POST})
    public Object readyLogin(@RequestBody String json){
        if(StringUtils.isNotBlank(json)){
            try {
                JSONObject jsons = (JSONObject) JSON.parse(json);
                String name = jsons.getString("userName");
                User userInfo = userService.findUserByName(name);
                if(userInfo == null)return ReturnMap.getReturnMap(400,"用户不存在");
                String random = UUID.randomUUID().toString();
                userInfo.setRandom(random);
                userService.updateRandom(userInfo);
                Map m = new HashMap();
                m.put("salt",userInfo.getUserName()+userInfo.getSalt());
                m.put("random",random);
                return ReturnMap.getReturnMapData(200,"请求成功",m);
            } catch (Exception e) {
                e.printStackTrace();
                return ReturnMap.getReturnMap(400,"系统异常");
            }

        }else{
            return ReturnMap.getReturnMap(400,"非法请求");
        }
    }
    /**
     * 正式登陆
     * */
    @RequestMapping(value ="/login",method = {RequestMethod.POST})
    public Object login(@RequestBody String json){
        if(StringUtils.isNotBlank(json)){
            try {
                JSONObject jsons = (JSONObject) JSON.parse(json);
                JSONObject info = jsons.getJSONObject("json");
                String userName = info.getString("userName");
                String password = info.getString("password");
                Subject subject = SecurityUtils.getSubject();
                UsernamePasswordToken token = new UsernamePasswordToken(userName,password);
                subject.login(token);
//                userService.loginLog(tempUser);//保存登录日志未实现
                Map m = new HashMap();
                m.put("token",subject.getSession().getId());
                //查询学校状态
                sendService.sendStateMessageByUser(false);
                return ReturnMap.getReturnMapData(200,"登录成功",m);
            } catch (IncorrectCredentialsException e) {
                return ReturnMap.getReturnMap(400,"密码错误");
            } catch (LockedAccountException e) {
                return ReturnMap.getReturnMap(400,"登录失败，该用户已被冻结");
            } catch (UnknownAccountException e) {
                return ReturnMap.getReturnMap(400,"用户不存在");
            } catch (ExcessiveAttemptsException e) {
                return ReturnMap.getReturnMap(400, "密码错误次数超过限制,账号被锁定2分钟");
            } catch (Exception e) {
                return ReturnMap.getReturnMap(400,"系统异常");
            }

        }else{
            return ReturnMap.getReturnMap(400,"输入不正确");
        }
    }

    /**
     * 未登录
     * */
    @RequestMapping(value = "/unauth")
    public Object unauth() {
        return ReturnMap.getReturnMap(303,"未登录");
    }

    /**
     * 注销
     * */
    @RequestMapping(value = "/mylogout", method = {RequestMethod.POST})
    public Object logout() {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            cache.removeCacheUser((String)subject.getSession().getId());
            subject.logout();
        }
        return ReturnMap.getReturnMap(200,"注销成功");
    }

    /**
     * 注册账号,超级管理员+注册权限才可以注册
     * */
    @RequiresRoles("root")
    @RequiresPermissions("regist")
    @RequestMapping(value = "/regist", method = {RequestMethod.POST})
    public Object regiest(@RequestBody String json) {
        try {
            JSONObject jsons = (JSONObject) JSON.parse(json);
            JSONObject info = jsons.getJSONObject("json");
            String name = info.getString("name");
            String pass = info.getString("pass");
            long roleId = info.getLongValue("role");
            if(StringUtils.isNotBlank(name) && StringUtils.isNotBlank(pass)){
                userService.regist(name, pass,roleId);
                return ReturnMap.getReturnMap(200,"注册成功");
            }
            return ReturnMap.getReturnMap(400,"不能提交空");
        } catch (OtherException e) {
            return ReturnMap.getReturnMap(400,e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return ReturnMap.getReturnMap(400,"注册失败");
        }
    }


    /**
     * 改密码
     * */
    @RequestMapping(value = "/changePassWord", method = {RequestMethod.POST})
    public Object changePassWord(@RequestBody String json) {
        try {
            JSONObject jsons = (JSONObject) JSON.parse(json);
            String password = jsons.getString("password");
            if(StringUtils.isBlank(password)){
                return ReturnMap.getReturnMap(400,"不能输入空");
            }else{
                userService.changePassWord(password);
                Subject subject = SecurityUtils.getSubject();
                if (subject.isAuthenticated()) {
                    cache.removeCacheUser((String)subject.getSession().getId());
                    subject.logout();
                }
                return ReturnMap.getReturnMap(200,"修改成功");
            }
        } catch (OtherException e) {
            return ReturnMap.getReturnMap(400,e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return ReturnMap.getReturnMap(400,"修改失败");
        }
    }

    /**
     * 获取角色
     * */
    @RequestMapping(value = "/getRoles", method = {RequestMethod.POST})
    public Object getRoles() {
        try {
            List<Role> list = roleService.findAllRoles();
            return ReturnMap.getReturnMapData(200,"成功",list);
        } catch (Exception e) {
            e.printStackTrace();
            return ReturnMap.getReturnMap(400,"系统异常");
        }
    }

    /**
     * 获取用户
     * */
    @RequiresRoles("root")
    @RequestMapping(value = "/getUser", method = {RequestMethod.POST})
    public Object getUsers() {
        try {
            List<User> list = userService.findAllUser();
            return ReturnMap.getReturnMapData(200,"成功",list);
        } catch (Exception e) {
            e.printStackTrace();
            return ReturnMap.getReturnMap(400,"系统异常");
        }
    }

    @RequiresRoles("root")
    @RequestMapping(value = "/lockUser",method = {RequestMethod.POST})
    public Object lockUser(@RequestBody String json){
        try{
            JSONObject jsons = (JSONObject) JSON.parse(json);
            long id = jsons.getLongValue("id");
            int lock = jsons.getIntValue("lock");
            if(id != 0)
            userService.lockUser(id,lock);
            if(lock == 0){
                return ReturnMap.getReturnMap(200,"解锁成功");
            }
            return ReturnMap.getReturnMap(200,"锁定成功");
        }catch (Exception e){
            e.printStackTrace();
            return ReturnMap.getReturnMap(400,"系统异常");
        }
    }

    @RequiresRoles("root")
    @RequestMapping(value = "/changerole",method = {RequestMethod.POST})
    public Object changerole(@RequestBody String json){
        try{
            JSONObject jsons = (JSONObject) JSON.parse(json);
            long id = jsons.getLongValue("id");
            long role = jsons.getLongValue("role");
            if(id != 0 && role != 0) userService.changeRole(id,role);
            return ReturnMap.getReturnMap(200,"变更成功");
        }catch (Exception e){
            e.printStackTrace();
            return ReturnMap.getReturnMap(400,"系统异常");
        }
    }

}
